package com.javasee.rain.stock.service;

import com.javasee.rain.stock.mapper.StockAlertMapper;
import com.javasee.rain.stock.model.StockAlert;
import com.javasee.rain.stock.model.StockBasic;
import com.javasee.rain.stock.util.PinyinUtil;
import com.javasee.rain.stock.util.StockCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 个股异动服务类
 * 
 * @author : xinyanfei
 * @date : 2025/10/11
 * Copyright (c) 2025, 京东商城 All Rights Reserved.
 */
@RestController
@RequestMapping("/api/stock-alert")
@CrossOrigin(origins = "*") // 允许跨域访问
public class StockAlertService {

    @Autowired
    private StockAlertMapper stockAlertMapper;

    /**
     * 获取所有股票基本信息
     * 
     * @return 股票基本信息列表
     */
    @GetMapping("/stocks")
    public ResponseEntity<Map<String, Object>> getAllStocks() {
        final String cacheKey = "all_stocks";
        try {
            // 尝试从缓存获取数据
            List<StockBasic> stockList = StockCacheUtil.get(cacheKey);
            
            if (stockList == null) {
                // 缓存未命中，从数据库查询
                System.out.println("缓存未命中，从数据库查询股票列表...");
                stockList = stockAlertMapper.selectAllStocks();
                
                // 为每个股票生成拼音首字母
                for (StockBasic stock : stockList) {
                    stock.setPinyin(PinyinUtil.getStockPinyinKey(stock.getName()));
                }
                
                // 存入缓存
                StockCacheUtil.put(cacheKey, stockList);
                System.out.println("股票列表已缓存，记录数: " + stockList.size());
            } else {
                System.out.println("从缓存获取股票列表，记录数: " + stockList.size());
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功");
            response.put("data", stockList);

            System.out.println("股票列表查询成功，记录数: " + stockList.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("查询股票列表失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * 根据关键字搜索股票信息（支持代码、名称、拼音首字母搜索）
     * 
     * @param keyword 搜索关键字
     * @return 股票基本信息列表
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchStocks(@RequestParam String keyword) {
        try {
            if (StringUtils.isEmpty(keyword)) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("message", "搜索关键字不能为空");
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }

            String trimmedKeyword = keyword.trim().toUpperCase();
            
            // 先通过数据库查询代码和名称匹配的股票
            List<StockBasic> dbStockList = stockAlertMapper.selectStocksByKeyword(keyword.trim());
            
            // 尝试从缓存获取所有股票用于拼音匹配
            List<StockBasic> allStocks = StockCacheUtil.get("all_stocks");
            if (allStocks == null) {
                // 如果缓存中没有，从数据库查询并缓存
                allStocks = stockAlertMapper.selectAllStocks();
                for (StockBasic stock : allStocks) {
                    stock.setPinyin(PinyinUtil.getStockPinyinKey(stock.getName()));
                }
                StockCacheUtil.put("all_stocks", allStocks);
            }
            
            // 存储最终结果
            Set<String> existingCodes = new HashSet<>();
            List<StockBasic> resultList = new ArrayList<>();
            
            // 添加数据库查询结果（优先级高）
            for (StockBasic stock : dbStockList) {
                stock.setPinyin(PinyinUtil.getStockPinyinKey(stock.getName()));
                resultList.add(stock);
                existingCodes.add(stock.getCode());
            }
            
            // 进行拼音首字母匹配
            for (StockBasic stock : allStocks) {
                if (!existingCodes.contains(stock.getCode())) {
                    String pinyin = PinyinUtil.getStockPinyinKey(stock.getName());
                    stock.setPinyin(pinyin);
                    
                    // 检查拼音首字母是否匹配
                    if (pinyin.contains(trimmedKeyword)) {
                        resultList.add(stock);
                        existingCodes.add(stock.getCode());
                    }
                }
            }
            
            // 按匹配度排序
            resultList.sort((a, b) -> {
                String codeA = a.getCode();
                String codeB = b.getCode();
                String nameA = a.getName();
                String nameB = b.getName();
                String pinyinA = a.getPinyin();
                String pinyinB = b.getPinyin();
                
                // 代码前缀匹配优先级最高
                boolean aCodePrefix = codeA.startsWith(keyword.trim());
                boolean bCodePrefix = codeB.startsWith(keyword.trim());
                if (aCodePrefix && !bCodePrefix) return -1;
                if (!aCodePrefix && bCodePrefix) return 1;
                
                // 名称前缀匹配优先级第二
                boolean aNamePrefix = nameA.startsWith(keyword.trim());
                boolean bNamePrefix = nameB.startsWith(keyword.trim());
                if (aNamePrefix && !bNamePrefix) return -1;
                if (!aNamePrefix && bNamePrefix) return 1;
                
                // 拼音前缀匹配优先级第三
                boolean aPinyinPrefix = pinyinA.startsWith(trimmedKeyword);
                boolean bPinyinPrefix = pinyinB.startsWith(trimmedKeyword);
                if (aPinyinPrefix && !bPinyinPrefix) return -1;
                if (!aPinyinPrefix && bPinyinPrefix) return 1;
                
                // 最后按代码排序
                return codeA.compareTo(codeB);
            });
            
            // 限制结果数量
            if (resultList.size() > 50) {
                resultList = resultList.subList(0, 50);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功");
            response.put("data", resultList);

            System.out.println("股票搜索成功，关键字: " + keyword + ", 记录数: " + resultList.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("搜索股票失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * 根据股票代码获取个股异动数据
     * 
     * @param stockCode 股票代码
     * @return 个股异动数据列表
     */
    @GetMapping("/{stockCode}")
    public ResponseEntity<Map<String, Object>> getStockAlertByCode(@PathVariable String stockCode) {
        try {
            List<StockAlert> stockAlertList = stockAlertMapper.selectStockAlertByCode(stockCode);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功");
            response.put("data", stockAlertList);

            System.out.println("个股异动数据查询成功，股票代码: " + stockCode + ", 记录数: " + stockAlertList.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("查询个股异动数据失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * 缓存管理接口 - 清除股票列表缓存
     * 
     * @return 操作结果
     */
    @DeleteMapping("/cache")
    public ResponseEntity<Map<String, Object>> clearStockCache() {
        try {
            StockCacheUtil.remove("all_stocks");
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "股票列表缓存已清除");
            response.put("data", null);
            
            System.out.println("股票列表缓存已手动清除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("清除缓存失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "清除缓存失败: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * 缓存管理接口 - 获取缓存信息
     * 
     * @return 缓存信息
     */
    @GetMapping("/cache/info")
    public ResponseEntity<Map<String, Object>> getCacheInfo() {
        try {
            String cacheInfo = StockCacheUtil.getCacheInfo();
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功");
            response.put("data", cacheInfo);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("获取缓存信息失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取缓存信息失败: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }

    /**
     * 缓存管理接口 - 清除过期缓存
     * 
     * @return 操作结果
     */
    @DeleteMapping("/cache/expired")
    public ResponseEntity<Map<String, Object>> clearExpiredCache() {
        try {
            StockCacheUtil.clearExpired();
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "过期缓存已清除");
            response.put("data", null);
            
            System.out.println("过期缓存已自动清除");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("清除过期缓存失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "清除过期缓存失败: " + e.getMessage());
            errorResponse.put("data", null);

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }
}